package cn.wizzer.app.web.modules.controllers.bus.equipment;

import cn.wizzer.app.bus.modules.models.equipment.BusEquipment;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import cn.wizzer.app.bus.modules.services.BusEquipmentService;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author tcjinxiu.com
 * @time 2024-04-11 10:19:44
 *
 */
@IocBean
@At("/platform/bus/equipment")
public class BusEquipmentController {
private static final Log log = Logs.get();
	@Inject
	BusEquipmentService busEquipmentService;
	@Inject
	private SysDictService sysDictService;
	@Inject
	private SysUnitService sysUnitService;
	@Inject
	private SysUserService sysUserService;

	@At("")
	@Ok("beetl:/platform/bus/equipment/index.html")
	@RequiresAuthentication
	public void index(HttpServletRequest req) {
		req.setAttribute("userId",StringUtil.getPlatformUid());
		req.setAttribute("statusMap", JSONObject.fromObject(sysDictService.getCodeMap("equipmentStatus")));
		req.setAttribute("statusOptions", JSONArray.fromObject(sysDictService.dictCodeTree("equipmentStatus")));
		req.setAttribute("calculateMap", JSONObject.fromObject(sysDictService.getCodeMap("calculate")));
		req.setAttribute("calculateOptions", JSONArray.fromObject(sysDictService.dictCodeTree("calculate")));
		req.setAttribute("calculateCycleTypeMap", JSONObject.fromObject(sysDictService.getCodeMap("calculateCycleType")));
		req.setAttribute("calculateCycleTypeOptions", JSONArray.fromObject(sysDictService.dictCodeTree("calculateCycleType")));

		req.setAttribute("unitOptions", JSONArray.fromObject(sysUnitService.getJybmTree()));
		req.setAttribute("userOptions", JSONArray.fromObject(sysUserService.getUserS("")));

	}



	@At
	@Ok("json:full")
	@RequiresAuthentication
	/*@RequiresPermissions("equipment.index.data")*///不要权限，因为其它功能需要读取
	public Object data(@Param("code") String code, @Param("name") String name,@Param("status") String status,
					   @Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize
	, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
		try {
			String sql = "select e.*,ur.username as managerName,ut.name as applyName from bus_equipment e  " +
					"left join sys_user ur on ur.id=e.managerBy " +
					"left join sys_unit ut on ut.id = e.applyDept where e.delFlag=0 ";
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(status)){
				String[] st =  status.split(",");
				if(st.length>0){
					sql+= " and ("+ Arrays.stream(st).map(t->(" e.status = "+t+" ")).collect(Collectors.joining("or"))+") ";
				}else{
					sql+= " and  e.status = '"+status+"' ";
				}
			}
			//数据权限
			sql+= " and e.opBy in ( SELECT id FROM sys_user WHERE unitid = '"+StringUtil.getPlatformUser().getUnitid()+"' ) ";
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by e."+pageOrderName+" asc,e.code asc ";
				} else {
					sql+= " order by e."+pageOrderName+" desc,e.code asc ";
				}
			}else{
				sql+= " order by e.code asc ";
			}
			return Result.success().addData(busEquipmentService.listPage(pageNumber, pageSize, Sqls.create(sql)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	/*@RequiresPermissions("equipment.index.data")*///不要权限，因为其它功能需要读取
	public Object dataIndex(@Param("code") String code, @Param("name") String name,@Param("status") String status,
							@Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize
			, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
		try {
			String sql = "select e.*,ur.username as managerName,ut.name as applyName from bus_equipment e  " +
					"left join sys_user ur on ur.id=e.managerBy " +
					"left join sys_unit ut on ut.id = e.applyDept where e.delFlag=0 ";
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(status)){
				sql+= " and  e.status = '"+status+"' ";
			}
			//数据权限
			sql+= StringUtil.dataScopeFilter("e");
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by e."+pageOrderName+" asc,e.code asc ";
				} else {
					sql+= " order by e."+pageOrderName+" desc,e.code asc ";
				}
			}else{
				sql+= " order by e.code asc ";
			}
			return Result.success().addData(busEquipmentService.listPage(pageNumber, pageSize, Sqls.create(sql)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
	}

	@At
	@Ok("json")
	@RequiresPermissions("equipment.index.add")
	@SLog(tag = "Add", msg = "Add:bus_equipment")
	public Object addDo(@Param("..") BusEquipment equipment, HttpServletRequest req) {
		try {
			busEquipmentService.insert(equipment);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At("/detail/?")
	@Ok("json")
	@RequiresAuthentication
	public Object detail(String id) {
		try {
			return Result.success("system.success").addData(busEquipmentService.fetch(id));
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At
	@Ok("json")
	@RequiresPermissions("equipment.index.edit")
	@SLog(tag = "Edit", msg = "Edit:bus_equipment")
	public Object editDo(@Param("..") BusEquipment equipment, HttpServletRequest req) {
		try {
			busEquipmentService.updateIgnoreNull(equipment);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At({"/delete","/delete/?"})
	@Ok("json")
	@RequiresPermissions("equipment.index.delete")
	@SLog(tag = "Delete", msg = "Delete:bus_equipment")
	public Object delete(String id,@Param("ids") String[] ids, HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				busEquipmentService.vDelete(ids);
			}else{
				busEquipmentService.vDelete(id);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

}
